<?php
/**
 * Created by PhpStorm.
 * User: Hong
 * Date: 2018/3/17
 * Time: 15:15
 * Function:
 */

namespace Platform\Models\Organize;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;

class LeaderRole extends Model
{
    const DEFAULT_YES = 1;
    const DEFAULT_NO = 0;

    protected $table = 'leader_roles';
    /**
     * @var array
     */
    protected $guarded = [];

    /**
     * 绑定领导者表关系
     * @return HasMany
     */
    public function leaders() : HasMany
    {
        return $this->hasMany(Leader::class, 'role_id', 'id');
    }

    /**
     * 绑定组织表关系
     * @return BelongsTo
     */
    public function organize() : BelongsTo
    {
        return $this->belongsTo(Organize::class);
    }


    /**
     * 绑定权限表关系
     * @return BelongsToMany
     */
    public function permissions() : BelongsToMany
    {
        return $this->belongsToMany(LeaderPermission::class, 'leader_role_permissions', 'role_id', 'permission_id');
    }

    /**
     * 获取角色下的权限
     * @return array
     */
    public function getPermissions(){

        $permissions = LeaderPermission::get(['id','name','module','uri','method']);
        $role_permissions = [];
        foreach ($this->permissions as $permission) {
            foreach ($permission->toPermissions() as $method => $uri) {
                $role_permissions[$method][] = $uri;
            }
        }
        $data = LeaderPermission::makeData($permissions,$role_permissions);
        return $data;
    }
}